function calculate(s: string, digit = 3) {
  const stack: number[] = [];
  let sign = '+',
    n = 0,
    num = '',
    c;
  for (let i = 0; i <= s.length; i++) {
    c = s.charAt(i);
    if (c === ' ') continue;
    if ((c >= '0' && c <= '9') || c === '.') {
      num += c;
      continue;
    }
    n = Number(num);
    num = '';
    if (sign === '+') {
      stack.push(n);
    } else if (sign === '-') {
      stack.push(-n);
    } else if (sign === '*') {
      stack.push((stack.pop() as number) * n);
    } else if (sign === '/') {
      stack.push(Math.trunc((stack.pop() as number) / n));
    }
    sign = c;
    n = 0;
  }
  const reg = /^(([^0][0-9]+|0)\.([0-9]{1,2}))$/;
  const result = stack.reduce((acc, n) => acc + n, 0);
  return reg.test(result.toString()) ? result.toFixed(digit) : result;
}

export default calculate;
